package com.dps.omc.schedule;

import com.dps.omc.email.JobEmailService;
import com.dps.omc.enumer.EnumJobState;
import com.dps.omc.model.Job;
import com.dps.omc.model.Task;
import com.dps.omc.model.User;
import com.dps.omc.service.IJobService;
import com.dps.omc.service.ITaskService;
import com.dps.omc.task.message.EnumTaskState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lip on 2016-04-03.
 */
@Service
public class JobStatusTask extends BaseTask{

    @Autowired
    private IJobService jobService;
    @Autowired
    private ITaskService taskService;
    @Autowired
    private JobEmailService jobEmailService;
    public void execute() throws Exception {
        logInfo("JobStatusTask任务开始");
        List<Job> jobs = jobService.findList("status", EnumJobState.EXECUTED);
        User user = new User();
        user.setUserName("SYS");
        user.setRealName("SYS");
        for(Job job:jobs)
        {
            Boolean allFinish = this.jobTaskAllFinish(job);
            if(allFinish)
            {
                Boolean jobFail = this.isJobFail(job);
                if(jobFail)
                {
                    job.setStatus(EnumJobState.FAIL);
                    jobService.update(job,user);
//                    jobEmailService.sendJobMsg(job);
                    jobEmailService.sendByJobStatus(job);
                }
                else
                {
                    job.setStatus(EnumJobState.SUCC);
                    jobService.update(job,user);
                }
            }
        }

        logInfo("JobStatusTask任务结束");
    }

    private Boolean jobTaskAllFinish(Job job)
    {
        int allCount = taskService.findListByJobId(job.getId()).size();

        Map<String,Object> condition = new HashMap<>();
        condition.put("jobId",job.getId());
        condition.put("status", EnumTaskState.FAIL);
        int failCount = taskService.queryList(condition,"seq","asc").size();

        condition = new HashMap<>();
        condition.put("jobId",job.getId());
        condition.put("status", EnumTaskState.SUCC);
        int succCount = taskService.queryList(condition,"seq","asc").size();

        Boolean res = allCount>(failCount+succCount)?false:true;
        if(res)
        {
            job.setTaskSucc(succCount);
            job.setTaskFail(failCount);
            jobService.update(job);
        }
        return res;
//        return allCount>(failCount+succCount)?false:true;
    }

    private Boolean isJobFail(Job job)
    {
        List<Task> tasks = taskService.findListByJobId(job.getId());
        for(Task task:tasks)
        {
            if(task.getStatus().equals(EnumTaskState.FAIL))
            {
                return true;
            }
        }
        return false;
    }
}
